package com.ddzj.scaffold.config;

import com.ddzj.scaffold.filter.JwtFilter;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

/**
 * @Author:yangzibo
 * @CreateTime:2024-04-14 12:05
 * @Description:
 * @Version:1.0
 **/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
//@enableglobalmethodsecurity(prePostEnabled = true)// 保证post之前的注解可以使用
public class SecurityConfigurer {

    private static final Long CORS_MAX_AGE = 3600L;
    private static final List<String> CORS_ALLOWED_HEADERS = List.of("*");
    @Autowired
    private JwtFilter jwtFilter;
    @Autowired
    private LogoutHandler logoutHandler;


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                // 解决跨域
                .csrf(AbstractHttpConfigurer::disable)
                //.cors(corsCustomizer -> corsCustomizer.configurationSource(corsConfigurationSource()))
                //.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 指定 登录鉴权 处理类
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                // 鉴权白名单, 配置绕过鉴权的接口
                .authorizeHttpRequests(authorized -> authorized
                        //.requestMatchers("/api/v1/management/**").hasAnyRole(ADMIN.name(), MANAGER.name())
                        //.requestMatchers(getRequestMatchersList().stream().toArray(String[]::new)).permitAll()
                        .requestMatchers("/login").permitAll()
//                        .requestMatchers("/test").permitAll()
//                        .requestMatchers("/test/**").permitAll()
//                        .requestMatchers("/userRegister").permitAll()
//                        .requestMatchers("/userRegister/**").permitAll()
                        .requestMatchers(HttpMethod.OPTIONS).permitAll()
                        .anyRequest().authenticated()
                )
                /*.formLogin(from->
                {
                    from.loginPage("/")//跳转到自定义的登录页面
                            .loginProcessingUrl("")//处理前端的请求，与form表单的action一致
                            .defaultSuccessUrl("/");//默认请求成功知乎跳转页面，直接访问登录页面
                })*/
                /*.logout(logout ->
                        logout.logoutUrl("/logout")

                                .addLogoutHandler(logoutHandler)
                                .logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext())
                )*/
                // 自定义异常处理
                /*.exceptionHandling(exceptionHandling -> exceptionHandling
                        .accessDeniedHandler(jwtAccessDeniedHandler)
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                )*/
                .build();
    }

    private List<String> getRequestMatchersList(){
        return Lists.newArrayList();
    }

    /**
     * CORS配置源, 解决跨域
     *
     * @return {@link CorsConfigurationSource}
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(CORS_ALLOWED_HEADERS); //同源配置，*表示任何请求都视为同源，若需指定ip和端口可以改为如“localhost：8080”，多个以“，”分隔；
        corsConfiguration.setAllowedMethods(CORS_ALLOWED_HEADERS);//header，允许哪些header，本案中使用的是token，此处可将*替换为token；
        corsConfiguration.setAllowedOrigins(CORS_ALLOWED_HEADERS); //允许的请求方法，PSOT、GET等
        corsConfiguration.setMaxAge(CORS_MAX_AGE);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);//配置允许跨域访问的url
        return source;
    }

}
